package com.mls.logindemo.support;

import com.auth0.jwt.interfaces.Claim;
import com.mls.logindemo.annotations.RequiredToken;
import com.mls.logindemo.enums.ResultCodeEnum;
import com.mls.logindemo.exceptions.BusinessException;
import com.mls.logindemo.utils.TokenUtils;
import com.mls.logindemo.utils.UserContext;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;

@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest
            , HttpServletResponse httpServletResponse, Object object) {
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        // 检查方法上是否有RequiredToken注解
        if (method.isAnnotationPresent(RequiredToken.class)) {
            // 若方法上有，则判断设置的是否false
            RequiredToken requiredToken = method.getAnnotation(RequiredToken.class);
            if (!requiredToken.value()) {
                // 若设置的required = false 则跳过验证
                return true;
            }
        } else if (handlerMethod.getBeanType().isAnnotationPresent(RequiredToken.class)) {
            // 若方法上没有注解则判断该方法的类上是否有RequiredToken注解
            // 若类上有，则判断设置的是否false
            RequiredToken requiredToken = handlerMethod.getBeanType().getAnnotation(RequiredToken.class);
            if (!requiredToken.value()) {
                // 若设置的required = false 则跳过验证
                return true;
            }
        }
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
        // 验证 token
        boolean verifyToken = TokenUtils.verifyToken(token);
        if (!verifyToken) {
            httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
            throw new BusinessException(ResultCodeEnum.EXPIRED_TOKEN);
        }
        // 保存当前登录信息
        Map<String, Claim> claims = TokenUtils.getClaims(token);
        UserContext.setToken(token);
        UserContext.setUserId(claims.get(UserContext.CONTEXT_KEY_USER_ID).asString());
        //UserContext.setLoginNo(claims.get(UserContext.CONTEXT_KEY_LOGIN_NO).asString());
        UserContext.setUserName(claims.get(UserContext.CONTEXT_KEY_USER_NAME).asString());
        //UserContext.setNickName(claims.get(UserContext.CONTEXT_KEY_USER_NICK_NAME).asString());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // ThreadLocal值清除，防止内存泄漏
        UserContext.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}